# This code is hosted on http://code.google.com/p/lenthorp/
# Freely available for use in applications, but should NOT be modified
# Email all comments to lenthorpresearch@gmail.com

import loadData
import matplotlib.pyplot as plt

def __getMatchingDates__(datas):
    # get matching dates for each series
    mySet = set(datas[0][0])
    for data in datas:
        mySet = set(mySet) & set(data[0])
    xVals = list(mySet)
    xVals.sort()
    return xVals
    

def plotSimple(dbName, tableName, dateLower = '', dateHigher = '', username='root'):
    data = loadData.LoadSQLDateRate(dbName, tableName, dateLower, dateHigher, username)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    xVals = data[0]
    yVals = data[1]
    ax.plot(xVals, yVals)
    plt.show()


def plotMultiple(dbName, tableNames, dateLower = '', dateHigher = '', username='root'):
    datas = []
    for tableName in tableNames:
        datas.append(loadData.LoadSQLDateRate(dbName, tableName, dateLower, dateHigher, username))
    fig = plt.figure()
    ax = fig.add_subplot(111)

    xVals = __getMatchingDates__(datas)

    for dataIdx in range(len(datas)):
        tableName = tableNames[dataIdx]
        data = datas[dataIdx]
        yVals = []
        for xVal in xVals:
            idx = data[0].index(xVal)
            yVals.append(data[1][idx])
        ax.plot(xVals, yVals, label=tableName)
    plt.legend(loc='upper left', shadow=True, fancybox=True)
    plt.xlabel('date')
    plt.ylabel('price')
    plt.show()


def plotMultipleRescaled(dbName, tableNames, dateLower = '', dateHigher = '', username='root'):
    datas = []
    for tableName in tableNames:
        datas.append(loadData.LoadSQLDateRate(dbName, tableName, dateLower, dateHigher, username))
    fig = plt.figure()
    ax = fig.add_subplot(111)

    xVals = __getMatchingDates__(datas)

    for dataIdx in range(len(datas)):
        tableName = tableNames[dataIdx]
        data = datas[dataIdx]
        idx = data[0].index(xVals[0])
        initial = data[1][idx]
        yVals = []
        for xVal in xVals:
            idx = data[0].index(xVal)
            yVals.append(float(data[1][idx])/initial)
        ax.plot(xVals, yVals, label=tableName)
    plt.legend(loc='upper left', shadow=True, fancybox=True)
    plt.xlabel('date')
    plt.ylabel('price (rescaled)')
    plt.show()
                    